import { exec } from 'child_process';
import { writeFile, readFile } from 'fs/promises';
import { resolve } from 'path';

async function generateBuildInfo() {
  try {
    // 获取Git信息的异步函数
    const getGitInfo = (command) =>
      new Promise((resolve, reject) => {
        exec(command, (error, stdout) => {
          if (error) {
            reject(`执行命令 "${command}" 时出错: ${error.message}`);
          } else {
            resolve(stdout.trim());
          }
        });
      });

    // 读取 package.json 中的版本号
    const packageJsonPath = resolve(process.cwd(), 'package.json');
    const packageJsonContent = await readFile(packageJsonPath, 'utf-8');
    const packageJson = JSON.parse(packageJsonContent);

    // 获取Git提交哈希值和分支名称
    const commitHash = await getGitInfo('git rev-parse --short HEAD');
    const branch = await getGitInfo('git rev-parse --abbrev-ref HEAD');
    const lastCommitMessage = await getGitInfo('git log -1 --pretty=%B');

    //自动生成版本号
    const semver = `v${packageJson.version}-${commitHash}`

    // 构建时间（上海时区）
    const buildTime = new Date().toLocaleString('zh-CN', {
      timeZone: 'Asia/Shanghai',
      hour12: false,
    });

    // 生成内容
    const buildInfo = {
      semver,
      commitHash,
      branch,
      buildTime,
      buildMode: process.env.NODE_ENV || 'development',
      lastCommitMessage,
    };

    // 写入public目录
    const outputPath = resolve(process.cwd(), 'src', 'version.json');
    await writeFile(outputPath, JSON.stringify(buildInfo, null, 2), 'utf-8');
    console.log('构建信息已生成:', buildInfo);
  } catch (error) {
    console.error('生成构建信息失败:', error);
    process.exit(1);
  }
}

generateBuildInfo();
